<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/home/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>任职管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <el-form :inline="true" class="searchForm">
      <el-form-item>
        <el-input v-model="keyword" clearable placeholder="请输入要搜索的关键字" @clear="clear"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="add" plain icon="el-icon-plus">任职</el-button>
      </el-form-item>

      <el-form-item>
        <el-select placeholder="选择年级" clearable filterable v-model="gradeId" @change="selectChange">
          <el-option v-for="item in gradeList" :key="item.id" :label="item.gradeName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select placeholder="选择分队" clearable filterable v-model="unitId" @change="selectChange">
          <el-option v-for="item in unitList" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select placeholder="选择职务" clearable filterable v-model="roleId" @change="selectChange">
          <el-option label="骨干" :value="0"></el-option>
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!-- 表单 -->

    <el-table :data="dataList" border stripe v-loading="loading" height="550px">
      <el-table-column type="index" align="center" label="序号"></el-table-column>
      <el-table-column label="姓名" prop="user.realName" min-width="80px" align="center"></el-table-column>
      <el-table-column label="分队" prop="unit.unitName" min-width="100px" align="center"></el-table-column>

      <el-table-column label="职务" min-width="100px" align="center">
        <template slot-scope="scope">
          <el-popover placement="top" trigger="hover">
            <el-tag type="success" size="normal" effect="plain">{{scope.row.unit?scope.row.unit.unitName:''}}</el-tag>
            <span slot="reference" class="roleName">{{scope.row.role?scope.row.role.roleName:''}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="授衔时间" prop="takeTime" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.takeTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="卸衔时间" prop="retireTime" min-width="100px" align="center">

      </el-table-column>
      <el-table-column label="操作" min-width="150px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="edit(scope.row)" icon="el-icon-s-tools">编辑</el-button>
          <el-button size="mini" type="danger" @click="remove(scope.row)" icon="el-icon-close">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination :current-page="page.page" :total="page.total" background layout="prev, pager, next" @current-change="currentChange">
    </el-pagination>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑" :visible.sync="dialogEdit" center v-loading="loading">
      <el-form class="form" :model="form" label-left label-width="100px" :rules="rules" ref="editForm">

        <el-form-item label="年级" prop="gradeId">
          <el-select placeholder="选择年级" filterable v-model="form.gradeId">
            <el-option v-for="item in gradeList" :key="item.id" :label="item.gradeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="队员" prop="userId">
          <el-cascader :options="userList" v-model="form.userId" filterable :show-all-levels="false" :props="{ expandTrigger: 'hover', emitPath:false}">
          </el-cascader>

        </el-form-item>

        <el-form-item label="分队" prop="unitId">
          <el-select placeholder="选择分队" filterable v-model="form.unitId">
            <el-option v-for="item in unitList" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职务" prop="gradeId">
          <el-select placeholder="选择职务" filterable v-model="form.roleId">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="授衔时间" prop="takeTime">
          <el-date-picker v-model="form.takeTime" type="date" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="卸衔时间" prop="retireTime">
          <el-date-picker v-model="form.retireTime" type="date" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doEdit('editForm')">确 定</el-button>
        <el-button @click="dialogEdit = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog title="新增" :visible.sync="dialogAdd" center v-loading="loading">
      <el-form class="form" :model="form" label-left label-width="100px" :rules="rules" ref="addForm">
        <el-form-item label="年级" prop="gradeId">
          <el-select placeholder="选择年级" filterable v-model="form.gradeId">
            <el-option v-for="item in gradeList" :key="item.id" :label="item.gradeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="队员" prop="userId">
          <el-cascader :options="userList" v-model="form.userId" filterable :show-all-levels="false" :props="{ expandTrigger: 'hover', emitPath:false}">
          </el-cascader>

        </el-form-item>

        <el-form-item label="分队" prop="unitId">
          <el-select placeholder="选择分队" filterable v-model="form.unitId">
            <el-option v-for="item in unitList" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职务" prop="gradeId">
          <el-select placeholder="选择职务" filterable v-model="form.roleId">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="卸衔时间" prop="retireTime">
          <el-date-picker v-model="form.retireTime" type="date" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doAdd('addForm')">确 定</el-button>
        <el-button @click="dialogAdd = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  adminUserRolePageApi as getPageApi,
  adminEditUserRoleApi as editApi,
  adminAddUserRoleApi as addApi,
  adminDelUserRoleApi as delApi,
  adminGetUnitListApi as getUnitList,
  adminGetGradeListApi as getGradeList,
  adminGetRoleListApi as getRoleList,
  adminGetUnitUserListApi as getUserList,
} from "@/api/admin.js";
export default {
  inject: ["reload"],
  data() {
    return {
      //表格展示数据
      dataList: [],
      //分页数据
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      //加载
      loading: false,
      //表单数据
      form: {
        takeTime: null,
        retireTime: null,
        userId: null,
        unitId: null,
        gradeId: null,
        roleId: null,
      }, //表单数据
      keyword: "", //关键字
      dialogEdit: false, //显示编辑对话款
      dialogAdd: false, //显示编辑对话款
      //表单校验
      rules: {
        userId: [
          {
            required: true,
            message: "请选择队员",
            trigger: "change",
          },
        ],
        roleId: {
          required: true,
          message: "请选择职务",
          trigger: "change",
        },
        gradeId: {
          required: true,
          message: "请选择年级",
          trigger: "change",
        },
        unitId: {
          required: true,
          message: "请选择分队",
          trigger: "change",
        },
      },
      unitList: [],
      gradeList: [],
      userList: [],
      roleList: [],
      userId: null,
      unitId: null,
      gradeId: null,
      roleId: 0,
    };
  },
  methods: {
    //获取数据列表
    getList(
      page = this.page.page,
      limit = this.page.limit,
      keyword = this.keyword,
      gradeId = this.gradeId,
      unitId = this.unitId,
      roleId = this.roleId
    ) {
      let queryParam = {
        page,
        limit,
        keyword,
        gradeId,
        unitId,
        roleId,
      };
      getPageApi(queryParam)
        .then((res) => {
          this.loading = true;
          const result = res.data;
          if (result.status === 200) {
            this.dataList = result.data.content;
            this.page.total = result.data.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    //分页
    currentChange(e) {
      this.page.page = e;
      this.getList();
    },
    //打开编辑对话款
    edit(e) {
      this.form.roleId = e.role.id;
      this.form.unitId = e.unit.id;
      this.form.userId = e.user.id;
      this.form.gradeId = e.grade.id;
      this.form.retireTime = new Date(e.retireTime);
      this.form.takeTime = new Date(e.takeTime);
      this.dialogEdit = true;
    },
    //执行编辑操作
    doEdit(e) {
      this.$refs[e].validate((valid) => {
        if (valid) {
          editApi(this.form)
            .then((res) => {
              this.loading = true;
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("修改成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.loading = false;
              this.dialogEdit = false;
              this.reload();
            });
        }
      });
    },
    //打开添加对话款
    add() {
      this.form = {};
      this.dialogAdd = true;
    },
    //执行添加操作
    doAdd(e) {
      this.$refs[e].validate((valid) => {
        if (valid) {
          addApi(this.form)
            .then((res) => {
              this.loading = true;
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("添加成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.loading = false;
              this.dialogAdd = false;
              this.reload();
            });
        }
      });
    },
    //删除
    remove(e) {
      this.$confirm("确认要删除吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          delApi({
            userId: e.user.id,
            roleId: e.role.id,
            unitId: e.unit.id,
            gradeId: e.grade.id,
          })
            .then((res) => {
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("删除成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.reload();
            });
        })
        .catch(() => {
          return;
        });
    },
    //批量删除
    dels() {
      const ids = this.select.map((role) => {
        return role.id;
      });
      const data = { ids };
      this.$confirm("确认要删除吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          delsApi(data)
            .then((res) => {
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("删除成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.reload();
            });
        })
        .catch(() => {
          return;
        });
    },
    //搜索
    search() {
      this.getList();
    },
    //清空文本框
    clear() {
      this.getList();
    },

    //获取年级列表
    getGradeList() {
      getGradeList().then((res) => {
        const result = res.data;
        if (result.status == 200) {
          this.gradeList = result.data;
        }
      });
    },
    //获取分队列表
    getUnitList() {
      getUnitList().then((res) => {
        const result = res.data;
        this.unitList = result.data;
      });
    },
    //获取分队队员列表
    getUserList() {
      getUserList().then((res) => {
        const result = res.data;
        if (result.status == 200) {
          result.data.forEach((unit) => {
            this.userList.push({
              label: unit.unitName,
              value: "unit-" + unit.id,
              children: unit.gradeList.map((grade) => {
                return {
                  label: grade.gradeName,
                  value: "grade-" + grade.id,
                  children: grade.userList.map((user) => {
                    return {
                      label: user.realName,
                      value: user.id,
                    };
                  }),
                };
              }),
            });
          });
        }
      });
    },
    //获取角色列表
    getRoleList() {
      getRoleList().then((res) => {
        const result = res.data;
        this.roleList = result.data;
      });
    },
    //点击选择筛选条件
    selectChange() {
      this.getList();
    },
    detail(e) {
      this.$router.push("/admin/index/USER/detail/" + e.id);
    },
  },
  created() {
    this.getList();
    this.getGradeList();
    this.getUnitList();
    this.getUserList();
    this.getRoleList();
  },
};
</script>

<style scoped>
.el-tabs {
  margin-top: 50px;
}
.el-pagination {
  float: right;
  margin: 20px;
}
.searchForm {
  margin-left: 100px;
  margin-top: 20px;
}
.form {
  padding: 20px 50px;
}
.form .el-form-item {
  width: 300px;
  margin: 20px auto;
}
.roleName:hover {
  cursor: pointer;
}
</style>
